package com.jiepos.mpos.biz.service.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.CustomProfitDao;
import com.jiepos.mpos.common.entity.App_Custom_ProfitEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * @author Zhao.Jinkui
 * @version 1.0
 * @ProjectName: mpos
 * @Package com.jiepos.mpos.biz.service.service
 * @ClassName CustomProfitService
 * @history
 * @UpdateRemark []
 * @since 2017/10/8
 */
@Service
public class CustomProfitService extends BaseService {

	@Autowired
	private CustomProfitDao customProfitDao;

	/**
	 * 分页查询会员分润设置数据
	 * @param request 
	 * 
	 * @param pagination
	 * @param entity
	 * @return
	 */
	public Map findByCondition(HttpServletRequest request, Pagination pagination, App_Custom_ProfitEntity entity) {
		StringBuffer sqlBuf = getInitSql("P").append(", ");
		sqlBuf.append(" P.CUSTOM_PROFIT_UUID AS UUID, ")
				.append("        I.INS_CD || '-' || I.INS_CN_NM AS INS_CD_NAME, ")
				.append("(SELECT CODE_VAL || '-' || CODE_DESC FROM " + Table.T_APP_CODE_LIST + " WHERE CODE_TP = '"
						+ DBConstant.Code.DIRECT_CUSTOM_LEVEL
						+ "' AND CODE_VAL = P.DIRECT_CUSTOM_LEVEL) as DIRECT_CUSTOM_LEVEL, ")
				.append("(SELECT CODE_VAL || '-' || CODE_DESC FROM " + Table.T_APP_CODE_LIST + " WHERE CODE_TP = '"
						+ DBConstant.Code.INDIRECT_CUSTOM_LEVEL
						+ "' AND CODE_VAL = P.INDIRECT_CUSTOM_LEVEL) as INDIRECT_CUSTOM_LEVEL, ")
				.append("(SELECT CODE_VAL || '-' || CODE_DESC FROM " + Table.T_APP_CODE_LIST + " WHERE CODE_TP = '"
						+ DBConstant.Code.CUR_CUSTOM_LEVEL
						+ "' AND CODE_VAL = P.CUR_CUSTOM_LEVEL) as CUR_CUSTOM_LEVEL, ")
				.append("(SELECT CODE_VAL || '-' || CODE_DESC FROM " + Table.T_APP_CODE_LIST + " WHERE CODE_TP = '"
						+ DBConstant.Code.PROFIT_MODE
						+ "' AND CODE_VAL = P.PROFIT_MODE) as PROFIT_MODE, ")
				.append("(SELECT CODE_VAL || '-' || CODE_DESC FROM " + Table.T_APP_CODE_LIST + " WHERE CODE_TP = '"
						+ DBConstant.Code.PROFIT_TYPE
						+ "' AND CODE_VAL = P.PROFIT_TYPE) as PROFIT_TYPE, ")
				.append("(CASE WHEN P.INDIRECT_COMM is null then '' else (to_char(P.INDIRECT_COMM,'fm9999999990.00')||CASE P.PROFIT_MODE WHEN '2' THEN '%' END) END )  as INDIRECT_COMM, ")
				.append("(CASE WHEN P.DIRECT_COMM is null then '' else (to_char(P.DIRECT_COMM,'fm9999999990.00')||CASE P.PROFIT_MODE WHEN '2' THEN '%' END) END) as DIRECT_COMM, ")
				.append("(CASE WHEN P.CUR_COMM is null then '' else (to_char(P.CUR_COMM,'fm9999999990.00')||CASE P.PROFIT_MODE WHEN '2' THEN '%' END) END) as CUR_COMM ")
				.append("   FROM " + DBConstant.Table.T_APP_CUSTOM_PROFIT + " P LEFT JOIN "
						+ DBConstant.Table.T_APP_INS_INF + " I ")
				.append(" ON P.INS_UUID = I.INS_UUID ").append("   WHERE 1 = 1 ");
		// 参数集合
		List<String> params = new ArrayList<>();
		if (!StringUtils.isBlank(entity.getIns_uuid())) {
			sqlBuf.append("   AND P.INS_UUID = ? ");
			params.add(entity.getIns_uuid());
		}
		//分润类型
		if (!StringUtils.isBlank(entity.getProfit_type())) {
			sqlBuf.append("   AND P.profit_type = ? ");
			params.add(entity.getProfit_type());
		}
		pagination.queryString = sqlBuf.toString();
		pagination = super.getDirectInsAuthSql(request, pagination, "P", null);
		pagination = this.getOrderSql(pagination, "P");
		// 执行查询
		return customProfitDao.getPaginationMap(pagination, "P", params);
	}

	/**
	 * 根据UUID加载唯一会员分润设置信息
	 * 
	 * @param
	 * @return
	 */
	public App_Custom_ProfitEntity findByUUID(String custom_profit_uuid) {
		return customProfitDao.findByParam("custom_profit_uuid", custom_profit_uuid);
	}

	/**
	 * 保存会员分润设置(新增、修改)
	 * 
	 * @param entity
	 * @param map
	 */
	public String saveCustomProfit(App_Custom_ProfitEntity entity, Map map) {
		String isSuccess = SystemConstant.ERROR;
		//先判断失效的是否存在数据
		List<Map<String, Object>> result = this.checkInsProfitStatusDisabled(entity);
		StringBuffer delSql = new StringBuffer();
		delSql.append("delete from "+Table.T_APP_CUSTOM_PROFIT+" where rec_id = ?");
		//如果存在则先删除该记录
		if(!CollectionUtil.isEmpty(result)){
			result.forEach((tmpMap) -> customProfitDao.deleteById(delSql.toString(), tmpMap.get("REC_ID")));
		}
		// 以是否有uuid来区分操作
		if (!StringUtils.isBlank(entity.getCustom_profit_uuid())) {
			// 更新
			entity = (App_Custom_ProfitEntity) this.saveCommonData(entity, map, "update");
			List noChangeList = new ArrayList();
			noChangeList.add("custom_profit_uuid");
			noChangeList.add("rec_crt_ts");
			customProfitDao.update(entity, noChangeList);
			isSuccess = SystemConstant.SUCCESS;
		} else {
			// 新增
			entity = (App_Custom_ProfitEntity) this.saveCommonData(entity, map, null);
			entity.setCustom_profit_uuid(IDFactoryUtil.getUUID());
			customProfitDao.save(entity);
			isSuccess = SystemConstant.SUCCESS;
		}
		
		return isSuccess;

	}

	/**
	 * 检查机构是否已进行过会员分润设置
	 * 
	 * @param entity
	 * @return
	 */
	public String checkInsProfitStatus(App_Custom_ProfitEntity entity) {
		StringBuffer sqlBuf = new StringBuffer();
		String result = SystemConstant.ERROR;
		sqlBuf.append(" SELECT count(1) as count1 ").append("FROM ").append(DBConstant.Table.T_APP_CUSTOM_PROFIT)
				.append(" WHERE 1=1 AND REC_ST = '1' AND LAST_OPER_IN <> 'D' ");

		// 参数集合
		List<String> params = new ArrayList<>();
		if (!StringUtils.isBlank(entity.getCustom_profit_uuid())) {
			sqlBuf.append("and CUSTOM_PROFIT_UUID <> ? ");
			params.add(entity.getCustom_profit_uuid());
		}
		// 机构uuid
		if (!StringUtils.isBlank(entity.getIns_uuid())) {
			sqlBuf.append("and INS_UUID = ? ");
			params.add(entity.getIns_uuid());
		}
		//间接推荐人会员等级
		if (!StringUtils.isBlank(entity.getIndirect_custom_level())) {
			sqlBuf.append("and INDIRECT_CUSTOM_LEVEL = ? ");
			params.add(entity.getIndirect_custom_level());
		}
		//直接推荐人会员等级
		if (!StringUtils.isBlank(entity.getDirect_custom_level())) {
			sqlBuf.append("and DIRECT_CUSTOM_LEVEL = ? ");
			params.add(entity.getDirect_custom_level());
		}
		if (!StringUtils.isBlank(entity.getCur_custom_level())) {
			sqlBuf.append("and CUR_CUSTOM_LEVEL = ? ");
			params.add(entity.getCur_custom_level());
		}
		if (!StringUtils.isBlank(entity.getProfit_type())) {
			sqlBuf.append("and PROFIT_TYPE = ? ");
			params.add(entity.getProfit_type());
		}

		List<Map<String, Object>> list = customProfitDao.queryForList(sqlBuf.toString(), params);
		int count = NumberUtils.toInt(StringUtils.objToString(list.get(0).get("count1")));
		if(!(count > 0)){
			result = SystemConstant.SUCCESS;
		}
		return result;
	}
	
	
	/**
	 * 检查机构是否已进行过会员分润设置
	 * 
	 * @param entity
	 * @return
	 */
	public List<Map<String, Object>> checkInsProfitStatusDisabled(App_Custom_ProfitEntity entity) {
		StringBuffer sqlBuf = new StringBuffer();
		String result = SystemConstant.ERROR;
		sqlBuf.append(" SELECT * ").append("FROM ").append(DBConstant.Table.T_APP_CUSTOM_PROFIT)
				.append(" WHERE 1=1 AND REC_ST = '0' OR LAST_OPER_IN = 'D' ");

		// 参数集合
		List<String> params = new ArrayList<>();
		// 机构uuid
		if (!StringUtils.isBlank(entity.getIns_uuid())) {
			sqlBuf.append("and INS_UUID = ? ");
			params.add(entity.getIns_uuid());
		}
		//间接推荐人会员等级
		if (!StringUtils.isBlank(entity.getIndirect_custom_level())) {
			sqlBuf.append("and INDIRECT_CUSTOM_LEVEL = ? ");
			params.add(entity.getIndirect_custom_level());
		}
		//直接推荐人会员等级
		if (!StringUtils.isBlank(entity.getDirect_custom_level())) {
			sqlBuf.append("and DIRECT_CUSTOM_LEVEL = ? ");
			params.add(entity.getDirect_custom_level());
		}
		if (!StringUtils.isBlank(entity.getCur_custom_level())) {
			sqlBuf.append("and CUR_CUSTOM_LEVEL = ? ");
			params.add(entity.getCur_custom_level());
		}
		if (!StringUtils.isBlank(entity.getProfit_type())) {
			sqlBuf.append("and PROFIT_TYPE = ? ");
			params.add(entity.getProfit_type());
		}

		List<Map<String, Object>> list = customProfitDao.queryForList(sqlBuf.toString(), params);
		return list;
	}

	/**
	 * 删除记录（假删）
	 * @param request
	 * @param ids
	 * @return
	 */
	public void deleteCustomProfit(HttpServletRequest request, String ids) {
		customProfitDao.deleteByStatus("custom_profit_uuid", ids);
	}
}
